#!/bin/sh /etc/rc.common
#
# Copyright (C) 2015 OpenWrt-dist
# Copyright (C) 2016 fw867 <ffkykzs@gmail.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#

START=91

CONFIG=ss_server
CONFIG_FILE=/var/etc/$CONFIG.json
PID_FILE=/var/run/$CONFIG.pid
LOG_FILE=/var/log/$CONFIG.log

uci_get_by_type() {
	local index=0
	if [ -n $4 ]; then
		index=$4
	fi
	local ret=$(uci get $CONFIG.@$1[$index].$2 2>/dev/null)
	echo ${ret:=$3}
}

is_true() {
	case $1 in
		1|on|true|yes|enabled) echo 0;;
		*) echo 1;;
	esac
}

load_config() {
	ENABLED=$(uci_get_by_type global enable)
	return $(is_true $ENABLED)
}

start_server() {
	mkdir -p  /var/etc
	/usr/bin/ss-server -u \
	-c $CONFIG_FILE  \
	-f $PID_FILE  \
	>$LOG_FILE 2>&1 &
}

gen_config_file() {
	cat <<-EOF >$CONFIG_FILE
		{
		    "server": "0.0.0.0",
		    "server_port": $(uci_get_by_type server server_port),
			"local_address":"127.0.0.1",
			"local_port":1088,
		    "password": "$(uci_get_by_type server password)",
		    "timeout": $(uci_get_by_type server timeout 60),
		    "method": "$(uci_get_by_type server encrypt_method)",
		    "protocol": "$(uci_get_by_type server protocol)",
		    "protocol_param": "$(uci_get_by_type server protocol_param)",
		    "obfs": "$(uci_get_by_type server obfs)",
		    "obfs_param": "$(uci_get_by_type server obfs_param)",
			"connect_verbose_info": "$(uci_get_by_type server connect_verbose_info 0)",
		    "redirect": "$(uci_get_by_type server redirect)",
		    "fast_open": $(uci_get_by_type server fast_open)
		}
EOF
}


add_rule() {
	serverport=$(uci_get_by_type server server_port)
	iptables -I  INPUT -p tcp --dport  $serverport -m comment --comment "Rule For SSR_SERVER_TCP" -j ACCEPT
	iptables -I  INPUT -p udp --dport  $serverport -m comment --comment "Rule For SSR_SERVER_UDP" -j ACCEPT
}

del_rule() {
	ssr_tcp_nu=`iptables -L INPUT --line-num 2> /dev/null|grep "Rule For SSR_SERVER_TCP" |awk '{print $1}'`
	[ -n "$ssr_tcp_nu" ] && iptables -D INPUT $ssr_tcp_nu 2>/dev/null
	ssr_udp_nu=`iptables -L INPUT --line-num 2> /dev/null|grep "Rule For SSR_SERVER_UDP" |awk '{print $1}'`
	[ -n "$ssr_udp_nu" ] && iptables -D INPUT $ssr_udp_nu 2>/dev/null
}

start() {
	! load_config && exit 0
	gen_config_file "server"
	start_server	
	add_rule
}

stop() {
  del_rule
	kill -9 $(cat $PID_FILE) >/dev/null 2>&1
	rm -f $LOG_FILE
}

